﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace QldtSdh.Utils
{
    class XMLConvertObject
    {
        public static string Serialize<T>(T dataToSerialize)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                doc.AppendChild(docNode);
                Type obj = typeof(T);
                XmlNode rootNode = doc.CreateElement(obj.Name);
                doc.AppendChild(rootNode);
                System.Reflection.PropertyInfo[] propertyInfo = obj.GetProperties();
                foreach (System.Reflection.PropertyInfo info in propertyInfo)
                {
                    try
                    {
                        var data = info.GetValue(dataToSerialize, null).ToString();
                        if (data.Contains("System.Collections") || data.Contains("Data.Entity"))
                            continue;
                        XmlElement childNode = doc.CreateElement(info.Name);
                        childNode.InnerText = data.IsNullOrEmpty() ? "null" : data;
                        rootNode.AppendChild(childNode);
                    }
                    catch
                    {
                        continue;
                    }
                }
                return doc.OuterXml;
            }
            catch (Exception ex)
            {
                throw new Exception("Lỗi chuyển từ đối tượng sang XML. Chi tiết: " + ex.Message);
            }
        }
    }
}
